package service

import (
	"context"
	"crypto/rand"
	"fmt"
	"math/big"
	"time"

	"github.com/redis/go-redis/v9"
	"gopkg.in/gomail.v2"
)

type EmailConfig struct {
	Host     string
	Port     int
	Username string
	Password string
}

var emailConfig = &EmailConfig{
	Host:     "smtp.qq.com",
	Port:     587,
	Username: "your-qq@qq.com",     // 替换为您的QQ邮箱
	Password: "your-smtp-password", // 替换为您的SMTP授权码
}

func SendVerifyCode(ctx context.Context, redisClient *redis.Client, email string) error {
	// 生成6位验证码
	code := generateVerifyCode()

	// 创建邮件内容
	m := gomail.NewMessage()
	m.SetHeader("From", emailConfig.Username)
	m.SetHeader("To", email)
	m.SetHeader("Subject", "水滴筹验证码")
	m.SetBody("text/html", fmt.Sprintf(`
        <h3>您的验证码是：%s</h3>
        <p>验证码有效期为5分钟，请勿泄露给他人。</p>
    `, code))

	// 创建SMTP客户端
	d := gomail.NewDialer(emailConfig.Host, emailConfig.Port, emailConfig.Username, emailConfig.Password)

	// 发送邮件
	if err := d.DialAndSend(m); err != nil {
		return err
	}

	// 将验证码保存到Redis，设置5分钟过期
	return SaveVerifyCode(ctx, redisClient, email, code)
}

// 生成6位随机验证码
func generateVerifyCode() string {
	code := ""
	for i := 0; i < 6; i++ {
		num, _ := rand.Int(rand.Reader, big.NewInt(10))
		code += num.String()
	}
	return code
}

// 保存验证码到Redis
func SaveVerifyCode(ctx context.Context, redisClient *redis.Client, email, code string) error {
	key := fmt.Sprintf("verify_code:%s", email)
	return redisClient.Set(ctx, key, code, 5*time.Minute).Err()
}

// 验证验证码
func VerifyCode(ctx context.Context, redisClient *redis.Client, email, code string) bool {
	key := fmt.Sprintf("verify_code:%s", email)
	storedCode, err := redisClient.Get(ctx, key).Result()
	if err != nil {
		return false
	}
	return storedCode == code
}
